<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <title>修改表单并重新提交申请</title>
        <style>
           div,th,td {
                font-size: 12px;
           }
           td a {
               margin: 0px 2px;
           }
        </style>
    </head>
    <body>
        <div id="content">
            <div id="currentUser" style="color:green;font-weight:bold;font-size:14px;"></div>
            <div><a id="backTo" href='#'>返回</a></div>

            <div>&nbsp;</div>
            <div id="info">修改表单并重新提交申请</div>

            <div>-----以下为审批表单信息部分------</div>
            <div>&nbsp;</div>
            <div>
                <form id="flowInstanceForm">
                    
                </form>
            </div>

            <div>&nbsp;</div>
            <div>处理人列表</div>
			<table border="1" id="handlerList">
            </table>

            <div>&nbsp;</div>
            <div>
                <input type="button" onclick="validateFormField();" value="修改表单并重新提交申请">
            </div>


        </div>
        <script src="js/config.js"></script>
        <script src="js/jquery.min.js"></script>
        <script type="text/javascript">
            var contextPath = getContextPath();
            var userId = getQueryVariable("userId");
            var id = getQueryVariable("id");
            var orderId = getQueryVariable("orderId");
            var orderType = getQueryVariable("orderType");

            //返回按钮
            document.getElementById("backTo").href = contextPath + "/main.html?userId="+userId;

            $(function() {
                //模拟所有参与人员
                //lix：普通人员
                //zhaoyl：项目经理
                //liujh,linjh,huangjc：部门经理
                //xuw：总经理
                let arr = ['lix', 'zhaoyl', 'liujh', 'linjh', 'huangjc', 'xuw'];
                if(!arr.includes(userId)){
                    alert("未合法的userId，请查看main.html里面的定义.");
                    return;
                }
                //设置当前用户信息：
                document.getElementById("currentUser").innerHTML = "你是："+userId;
                //设置当前流程Key
                document.getElementById("info").innerHTML = "当前为表单修改，并重新提交流程环节，工单类型：<font color='red'>["+orderType+"]</font>";

                //加载出工单记录信息
                $.ajax({
                    url:  contextPath + "/workOrder/queryByOrderId",
                    data: JSON.stringify({
                        orderId: orderId
                    }),
                    type: 'post',
                    contentType: 'application/json;charset=utf-8',
                    dataType: "json",
                    success: function (res) {
                        let formData = res.formData
                        //同时加载出动态表单字段的数据
                        setFormData(formData);
                    },
                    error: function (result) {alert("加载出工单记录信息失败，内部错误.");}
                });

                //2.流程人选择内容区域，用于开启流程时动态选择审批人
                $.ajax({
                    url:  window.location.origin + contextPath + '/workOrderAssignee/selectSelective',
                    data: JSON.stringify({
                        orderId: orderType
                    }),
                    type: 'post',
                    contentType: 'application/json;charset=utf-8',
                    dataType: "json",
                    success: function (res) {

                        var htmlStr = "<tr>";
                            htmlStr += "<th>工单类型(order_id)</th>";
                            htmlStr += "<th>工单任务代理人的版本号(assignee_version)</th>";
                            htmlStr += "<th>工单任务代理人(assignee)</th>";
                            htmlStr += "<th>工单任务代理人的顺序(assigneeOrder)</th>";
                            htmlStr += "<th>任务(节点)名(task_name)</th>";
                            htmlStr += "<th>流程执行到此任务(节点)时的工单状态(order_status)</th>";
                        if(res.length >0){
                            var list = res;
                            for(var i=0;i<list.length;i++){
                                htmlStr += "<tr>";
                                htmlStr += "<td>"+list[i].orderId+"</td>";
                                htmlStr += "<td>"+list[i].assigneeVersion+"</td>";
                                htmlStr += "<td>"+list[i].assignee+"</td>";
                                htmlStr += "<td>"+list[i].assigneeOrder+"</td>";
                                htmlStr += "<td>"+list[i].taskName+"</td>";
                                htmlStr += "<td>"+list[i].orderStatus+"</td>";
                            }
                        }

                        document.getElementById("handlerList").innerHTML = htmlStr;
                        
                    },
                    error: function (result) {alert("加载流程节点配置及审批人列表失败，内部错误.");}
                });


            });

            //setFormData,设置动态form的内容
            function setFormData(formDataStr){
                //加载出表单的动态字段，然后设置到html中
                //动态构造Form表单的字段,根据flowKey查询出表单的字段列表，然后动态构造表单
                var formData = JSON.parse(formDataStr);
                $.ajax({
                    url:  contextPath + "/workFlowFormField/list",
                    data: JSON.stringify({
                        orderType: getQueryVariable("orderType")
                    }),
                    type: 'post',
                    contentType: 'application/json;charset=utf-8',
                    dataType: "json",
                    success: function (res) {
                        if(res.length >0){
                            var htmlStr = "";
                            var list = res;
                            for(var i=0;i<list.length;i++){

                                //文本框类型展示处理
                                if(list[i].fieldType === "text"){
                                    htmlStr += list[i].fieldCname+"-"+list[i].fieldName+':<input value="'+formData[list[i].fieldName]+'" type="text" name="'+list[i].fieldName+'" id="'+list[i].fieldName+'"><br>';
                                }else if(list[i].fieldType === "select"){
                                    //下拉选择框处理
                                    htmlStr += list[i].fieldCname+"-"+list[i].fieldName+':';
                                    
                                    htmlStr += '<select name="'+list[i].fieldName+'">';
                                    //遍历下拉列表选项
                                    var otherInfoArray = JSON.parse(list[i].otherInfo);
                                    otherInfoArray.map(function(item,index) {
                                        var selectedStr = item.value === formData[list[i].fieldName] ? "selected" :"";
                                        htmlStr += '<option '+selectedStr+' value ="'+item.value+'">'+item.label+'</option>';
                                    });
                                    htmlStr += '</select><br>'; 
                                }

                            }
                            document.getElementById("flowInstanceForm").innerHTML = htmlStr;
                        }
                    },
                    error: function (result) {alert("加载流程动态表单字段配置失败，内部错误.");}
                });

            }

            //validateFormField，表单字段较验
            function validateFormField(){

                //校验表单字段是不是填写完整
                $.ajax({
                    url:  contextPath + "/workFlowFormField/list",
                    data: JSON.stringify({
                        orderType: orderType
                    }),
                    type: 'post',
                    contentType: 'application/json;charset=utf-8',
                    dataType: "json",
                    success: function (res) {
                        
                        //遍历所有的字段进行校验
                        let validateSuccess = true;
                        if(res.length >0){
                            var list = res;
                            var formJson = serializeToJson($("#flowInstanceForm").serialize());
                            for(var i=0;i<list.length;i++){
                                if(formJson[list[i].fieldName] === undefined){
                                    alert(list[i].fieldCname+"-"+list[i].fieldName + " ,字段填写未完整！");
                                    validateSuccess = false;
                                    break;
                                }
                            }
                        }

                        if(validateSuccess){
                            startFlowInstance();
                        }
                    },
                    error: function (result) {alert("加载流程动态表单字段配置失败，内部错误.");}
                });

            }

            //开启一个新的流程
            function startFlowInstance(){
                //开启一个新流程
                var formJson = serializeToJson($("#flowInstanceForm").serialize());
                var params = {};
                params.orderType = orderType;
                params.userId = userId;
                params.orderId = orderId;
                params.formJson = formJson;

                if (window.confirm("修改表单并重新提交申请?")) {

                    //提交动态表单并开启新的流程
                    $.ajax({
                        url:  contextPath + "/workOrder/modificationWorkOrder",
                        data: JSON.stringify(params),
                        type: 'post',
                        contentType: 'application/json;charset=utf-8',
                        dataType: "json",
                        success: function (res) {
                            
                            alert("修改表单并重新提交申请成功.");
                            //返回
                            window.location.href = contextPath + "/main.html?userId="+userId;

                        },
                        error: function (result) {alert("修改表单并重新提交申请失败，内部错误.");}
                    });
                    
                } 


            }

            //获取浏览器地址上的url参数
            function getQueryVariable(variable){
                var query = window.location.search.substring(1);
                var vars = query.split("&");
                for (var i=0;i<vars.length;i++) {
                    var pair = vars[i].split("=");
                    if(pair[0] == variable){return pair[1];}
                }
                return "";
            }

            //参数并转换成对象Examples: &username=admin&age=19 -> {"username":"admin","age":19}
            function serializeToJson(urlString){
                const result = {} // 存参数得对象
                // 利用正则表达式
                urlString = "&" + urlString;
                let reg = /[?&][^?&]+=[^?&]+/g;
                const found = urlString.match(reg) ; //拿到有符合正则得字符串，输出为数组 [ '?name=home', '&age=20' ]
                if(found){
                    found.forEach(item => {
                        let temp = item.substring(1).split('='); // = 分割
                        let key = temp[0];
                        let value = temp[1];
                        result[key] = value
                    })
                }
                return result;
            }

            //设置select选中
            function set_select_checked(selectId, checkValue){
                var select = document.getElementById(selectId);
                for (var i = 0; i < select.options.length; i++){
                    if (select.options[i].value == checkValue){
                        select.options[i].selected = true;
                        break;
                    }
                }
            }

        </script>
    </body>
</html>